package vn.edu.uit.hotelbooking.activity;

import vn.edu.uit.hotelbooking.R;
import vn.edu.uit.hotelbooking.CustomView.CustomDialog;
import vn.edu.uit.hotelbooking.CustomView.CustomDialog.myOnPositiveClickListener;
import vn.edu.uit.hotelbooking.utils.UITPreferenceConstant;
import vn.edu.uit.hotelbooking.utils.UITPreferenceUtils;
import vn.edu.uit.service.UITService;
import vn.edu.uit.service.fetchers.UserFetcher;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Login activity
 * @author DQH
 * 
 */

public class LoginActivity extends Activity {
    public myOnPositiveClickListener myPositive;
    
    /** The dialog */
    private ProgressDialog dialog;
    
    /** The Email EditText */
    private EditText edtEmail;
    
    /** The Password EditText*/
    private EditText edtPassword;
    
    /** The Remember Account CheckBox*/
    private CheckBox cbRememberAccount;
    
    /** The Login Button*/
    private Button btnLogin;
    
    /** The status of request. 
     * Default status = -1. 
     * If status > 0: request success.*/
    private int status = -1;
    
    /** The handler to process  */
    Handler handler = new Handler(){

        /* (non-Javadoc)
         * @see android.os.Handler#handleMessage(android.os.Message)
         */
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), String.valueOf(status), Toast.LENGTH_SHORT).show();
            if (status > 0) {       //the request was successful
                
                //save token to SharedPreference
                UITPreferenceUtils.saveStringPref(getApplicationContext(),      
                        UITPreferenceConstant.TOKEN, UITService.TOKEN);                
                  
                if (cbRememberAccount.isChecked()) {        //remember user email and password for next time       
                    //save if remember was checked
                    UITPreferenceUtils.saveIntPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_REMEMBER, 1);
                    //save email to SharedPreference
                    UITPreferenceUtils.saveStringPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_EMAIL, edtEmail.getText().toString());
                    //save password to SharedPrference
                    UITPreferenceUtils.saveStringPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_PASSWORD, edtPassword.getText().toString());
                } else {                                    //reset email and password
                    //save if remember was not checked
                    UITPreferenceUtils.saveIntPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_REMEMBER, 0);
                    //save email to SharedPreference
                    UITPreferenceUtils.saveStringPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_EMAIL, "");
                    //save password to SharedPreference
                    UITPreferenceUtils.saveStringPref(getApplicationContext(),  
                            UITPreferenceConstant.USER_PASSWORD, "");
                }
                
                //start HomeActivity
                Intent in = new Intent(getApplicationContext(), HomeActivity.class);    
                startActivity(in);
                finish();
                
            } else {        // the request was failed, show dialog for user    
                myPositive = new myOnPositiveClickListener() {                    
                    @Override
                    public void onButtonClick() {
                        // TODO Auto-generated method stub                        
                    }
                };
                CustomDialog mydialog = new CustomDialog(LoginActivity.this, "Error", "Login failed. Please try again later.", false, R.drawable.star_gold_128, "OK", null, myPositive, null);
                AlertDialog myAlert = (AlertDialog)mydialog.OnCreateAlert();
                myAlert.show();  
            }
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);        
        edtEmail = (EditText)findViewById(R.id.edtEmail);
        edtPassword = (EditText)findViewById(R.id.edtPassword);
        cbRememberAccount = (CheckBox)findViewById(R.id.cbRememberAccount);
        btnLogin = (Button)findViewById(R.id.btnLogin);
        if(UITPreferenceUtils.getIntPref(getApplicationContext(), UITPreferenceConstant.USER_REMEMBER, 0) > 0) {
            cbRememberAccount.setChecked(true);
            String email = UITPreferenceUtils.getStringPref(getApplicationContext(), 
                        UITPreferenceConstant.USER_EMAIL, "");
            String password = UITPreferenceUtils.getStringPref(getApplicationContext(), 
                        UITPreferenceConstant.USER_PASSWORD, "");
            
            if(!email.equals("")) {
                edtEmail.setText(email);
            }
            if(!password.equals("")) {
                edtPassword.setText(password);
            }
        }
        //Set function for events listener
        btnLogin.setOnClickListener(LoginClick);        
    }
    
    /** The Login button function*/
    View.OnClickListener LoginClick = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(!checkInternetConnection()) {
                myPositive = new myOnPositiveClickListener() {                    
                    @Override
                    public void onButtonClick() {
                        // TODO Auto-generated method stub                        
                    }
                };
                CustomDialog mydialog = new CustomDialog(LoginActivity.this, "Error", "No internet connection.", false, R.drawable.star_gold_128, "OK", null, myPositive, null);
                AlertDialog myAlert = (AlertDialog)mydialog.OnCreateAlert();
                myAlert.show();  
            } else {
                dialog = ProgressDialog.show(LoginActivity.this, "Loadding", "Log in");
                new Thread(new Runnable() {
                    
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub                        
                        //send request to server to check login
                        status = UserFetcher.checkLogin(edtEmail.getText().toString(), 
                                edtPassword.getText().toString());                    
                        handler.sendEmptyMessage(0); 
                        
                    }
                }).start();
            }
        }
    };
    
    /** The checkInternetConnection function */
    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // check wifi and mobile internet connection
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }
}
